<template>
  <g class="connection" v-if="sourceNode && targetXY">
    <!-- 连接线路径 -->
    <path :d="pathData" :stroke="connection.style.strokeColor" :stroke-width="connection.style.strokeWidth"
      :stroke-dasharray="connection.style.strokeDasharray" fill="none" class="connection-path" @click="handleClick" />

    <!-- 箭头标记 -->
    <defs>
      <marker :id="`arrowhead-${connection.id}`" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
        <polygon points="0 0, 10 3.5, 0 7" :fill="connection.style.strokeColor" />
      </marker>
    </defs>

    <!-- 带箭头的路径 -->
    <path :d="pathData" :stroke="connection.style.strokeColor" :stroke-width="connection.style.strokeWidth"
      :stroke-dasharray="connection.style.strokeDasharray" fill="none" :marker-end="`url(#arrowhead-${connection.id})`"
      class="connection-arrow" />

    <!-- 连接线标签（可选） -->
    <text v-if="showLabel" :x="labelPosition.x" :y="labelPosition.y" class="connection-label" text-anchor="middle">
      {{ connection.id }}
    </text>
  </g>
</template>

<script>
import * as d3 from 'd3'
import { isPointInNode, getConnectionPoint } from '../util'
import { mapState, mapGetters,mapActions } from 'vuex'
export default {
  name: 'Connection',
  props: {
    connection: {
      type: Object,
      required: true
    },
    sourceNode: {
      type: Object,
      required: true
    },
    targetXY: {
      type: Object,
      required: false,
      default: null
    },
    showLabel: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState(['nodes']),
    ...mapGetters(['getNewConnectionPathTargetXY']),


    //获取起始节点和结束节点的连接点坐标
    sourcePoint() {
      const sourceXY = this.getConnectionPoint(this.sourceNode, this.connection.sourcePoint)
      console.log(`起始节点连接点坐标`, sourceXY);
      return sourceXY
    },

    targetPoint() {
      if (!this.targetXY) {
        return this.sourcePoint
      }
      const targetXY = {
        x: this.sourcePoint.x + this.targetXY.x,
        y: this.sourcePoint.y + this.targetXY.y
      }
      const targetNode = this.nodes.filter(node => isPointInNode(node, targetXY))
      const points = ['top', 'right', 'bottom', 'left']
      let targetPoints = []

      if (targetNode.length > 0) {
        targetPoints = points.map(point => {
          return{
            trget:getConnectionPoint(targetNode[0], point),
            point: point,
            targetNode: targetNode[0]
          }
        })
        console.log(`@@@`, targetPoints);
        
        this.updateTargetPoints(targetPoints)
      }
      this.updateTargetXY(targetXY)
      return targetXY
    },

    pathData() {
      return this.generatePath(this.sourcePoint, this.targetPoint)
    },

    labelPosition() {
      const midX = (this.sourcePoint.x + this.targetPoint.x) / 2
      const midY = (this.sourcePoint.y + this.targetPoint.y) / 2
      return { x: midX, y: midY }
    }
  },
  methods: {
        ...mapActions(['updateTargetPoints','updateTargetXY']),
    // 获取节点连接点的坐标
    getConnectionPoint(node, point) {
      const { x, y, style } = node
      const { width, height } = style
      switch (point) {
        case 'top':
          return { x: x + width / 2, y }
        case 'right':
          return { x: x + width, y: y + height / 2 }
        case 'bottom':
          return { x: x + width / 2, y: y + height }
        case 'left':
          return { x, y: y + height / 2 }
        default:
          return { x: x + width / 2, y: y + height / 2 }
      }
    },

    // 使用D3.js生成贝塞尔曲线路径
    generatePath(source, target) {
      const dx = target.x - source.x
      const dy = target.y - source.y

      // 计算控制点偏移量
      const offset = Math.min(Math.abs(dx), Math.abs(dy)) * 0.5 + 50

      // 根据连接方向调整控制点
      let cp1x, cp1y, cp2x, cp2y

      if (Math.abs(dx) > Math.abs(dy)) {
        // 水平方向为主
        cp1x = source.x + (dx > 0 ? offset : -offset)
        cp1y = source.y
        cp2x = target.x + (dx > 0 ? -offset : offset)
        cp2y = target.y
      } else {
        // 垂直方向为主
        cp1x = source.x
        cp1y = source.y + (dy > 0 ? offset : -offset)
        cp2x = target.x
        cp2y = target.y + (dy > 0 ? -offset : offset)
      }

      // 使用D3的曲线生成器
      const line = d3.line()
        .x(d => d[0])
        .y(d => d[1])
        .curve(d3.curveBasis)

      const points = [
        [source.x, source.y],
        [cp1x, cp1y],
        [cp2x, cp2y],
        [target.x, target.y]
      ]

      return line(points) || ''
    },

    // 处理连接线点击
    handleClick() {
      this.$emit('connection-select', this.connection.id)
      console.log(`选中连接线: ${this.connection.id}`)
    }
  }
}
</script>

<style scoped>
.connection-path {
  cursor: pointer;
  stroke-linecap: round;
  stroke-linejoin: round;
  transition: stroke-width 0.2s;
}

.connection-path:hover {
  stroke-width: 3px !important;
}

.connection-arrow {
  pointer-events: none;
}

.connection-label {
  font-size: 12px;
  fill: #666;
  pointer-events: none;
  user-select: none;
}

.connection:hover .connection-label {
  fill: #333;
}
</style>